"""
员工管理路由
"""
import json
from datetime import datetime
from flask import Blueprint, render_template, request, redirect, url_for, flash
from flask_login import login_required
from sqlalchemy import func

from app.extensions import db
from app.models.customer import Customer
from app.models.staff import Staff, StaffProject
from app.models.associations import CustomerStaff

staff_bp = Blueprint('staff', __name__, url_prefix='/staff')


@staff_bp.route('/')
@staff_bp.route('/management')
@login_required
def staff_management():
    """人员管理页面"""
    page = request.args.get('page', 1, type=int)
    search_name = request.args.get('search_name', '')
    search_position = request.args.get('search_position', '')
    search_is_manager = request.args.get('search_is_manager', '')
    
    query = Staff.query
    
    if search_name:
        query = query.filter(Staff.name.contains(search_name))
    if search_position:
        query = query.filter(Staff.position.contains(search_position))
    if search_is_manager:
        is_manager = search_is_manager == 'true'
        query = query.filter(Staff.is_general_manager == is_manager)
    
    staff_list = query.paginate(page=page, per_page=20, error_out=False)
    
    # 获取下拉选项数据
    positions = db.session.query(Staff.position).distinct().all()
    projects = db.session.query(Staff.project_name).distinct().all()
    customers = db.session.query(Customer.name).all()
    
    return render_template('staff/staff_management.html',
                         staff_list=staff_list,
                         positions=[p[0] for p in positions if p[0]],
                         projects=[p[0] for p in projects if p[0]],
                         customers=[c[0] for c in customers],
                         search_name=search_name,
                         search_position=search_position,
                         search_is_manager=search_is_manager)


@staff_bp.route('/add', methods=['POST'])
@login_required
def add_staff():
    """添加项目负责人"""
    try:
        staff = Staff(
            name=request.form.get('name'),
            project_name=request.form.get('project_name'),
            position=request.form.get('position'),
            specific_position=request.form.get('specific_position'),
            is_general_manager=request.form.get('is_general_manager') == 'on',
            phone=request.form.get('phone'),
            customers=json.dumps(request.form.getlist('customers')),
            project_level=request.form.get('project_level'),
            project_create_time=datetime.utcnow(),
            project_optimize_time=datetime.utcnow(),
            # 新增字段
            email=request.form.get('email', '')
        )
        
        db.session.add(staff)
        db.session.commit()
        flash('项目负责人添加成功')
    except Exception as e:
        db.session.rollback()
        flash(f'添加失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))


@staff_bp.route('/edit/<int:staff_id>', methods=['POST'])
@login_required
def edit_staff(staff_id):
    """编辑员工信息"""
    staff = Staff.query.get_or_404(staff_id)
    try:
        staff.name = request.form.get('name')
        staff.project_name = request.form.get('project_name')
        staff.position = request.form.get('position')
        staff.specific_position = request.form.get('specific_position')
        staff.is_general_manager = request.form.get('is_general_manager') == 'on'
        staff.phone = request.form.get('phone')
        staff.customers = json.dumps(request.form.getlist('customers'))
        staff.project_level = request.form.get('project_level')
        staff.email = request.form.get('email', '')
        staff.updated_at = datetime.utcnow()
        
        db.session.commit()
        flash('员工信息更新成功')
    except Exception as e:
        db.session.rollback()
        flash(f'更新失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))


@staff_bp.route('/delete/<int:staff_id>', methods=['POST'])
@login_required
def delete_staff(staff_id):
    """删除员工"""
    staff = Staff.query.get_or_404(staff_id)
    try:
        db.session.delete(staff)
        db.session.commit()
        flash('员工删除成功')
    except Exception as e:
        db.session.rollback()
        flash(f'删除失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))


@staff_bp.route('/add_project', methods=['POST'])
@login_required
def add_staff_project():
    """为员工添加项目关联"""
    try:
        staff_project = StaffProject(
            staff_id=request.form.get('staff_id'),
            project_name=request.form.get('project_name'),
            project_level=request.form.get('project_level'),
            position_in_project=request.form.get('position_in_project'),
            specific_position_in_project=request.form.get('specific_position_in_project'),
            role=request.form.get('role', '')
        )
        
        db.session.add(staff_project)
        db.session.commit()
        flash('项目关联添加成功')
    except Exception as e:
        db.session.rollback()
        flash(f'添加失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))


@staff_bp.route('/delete_project/<int:staff_project_id>', methods=['POST'])
@login_required
def delete_staff_project(staff_project_id):
    """删除员工项目关联"""
    try:
        staff_project = StaffProject.query.get_or_404(staff_project_id)
        db.session.delete(staff_project)
        db.session.commit()
        flash('项目关联删除成功')
    except Exception as e:
        db.session.rollback()
        flash(f'删除失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))


@staff_bp.route('/add_customer_relation', methods=['POST'])
@login_required
def add_customer_staff_relation():
    """添加客户-员工关联"""
    try:
        customer_staff = CustomerStaff(
            customer_id=request.form.get('customer_id'),
            staff_id=request.form.get('staff_id'),
            project_name=request.form.get('project_name'),
            relationship_type=request.form.get('relationship_type', '')
        )
        
        db.session.add(customer_staff)
        db.session.commit()
        flash('客户-员工关联添加成功')
    except Exception as e:
        db.session.rollback()
        flash(f'添加失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))


@staff_bp.route('/delete_customer_relation/<int:relation_id>', methods=['POST'])
@login_required
def delete_customer_staff_relation(relation_id):
    """删除客户-员工关联"""
    try:
        relation = CustomerStaff.query.get_or_404(relation_id)
        db.session.delete(relation)
        db.session.commit()
        flash('客户-员工关联删除成功')
    except Exception as e:
        db.session.rollback()
        flash(f'删除失败: {str(e)}')
    
    return redirect(url_for('staff.staff_management'))
